<?php

namespace App\Http\Controllers\Admin\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\PermissionRequest;
use App\Models\Permission;
use App\Transformers\Admin\PermissionTransformer;
use Dingo\Api\Http\Response;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    /**
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        // 获取顶级权限 并且联查所有子级
        $data = Permission::query()->where('pid', 0)
            ->with([
                'children:id,name,cn_name,guard_name,pid',
            ])
            ->get();

        return $this->response->collection($data, new PermissionTransformer());
    }

    /**
     * @param PermissionRequest $request
     * @return Response
     */
    public function store(PermissionRequest $request)
    {
        if ($request->hasAny('pid')) {
            $pid = Permission::query()
                ->select('pid')
                ->where('id', $request->input('pid'))
                ->first();

            if ($pid['pid'] != 0) {
                return $this->response->errorBadRequest('权限不能超过两级');
            }
        }

        // 获取传入的数据
        $data = $request->all();

        Permission::create($data);

        return $this->response->created();
    }

    /**
     * @param $id
     * @return Response|void
     */
    public function show($id)
    {
        // 获取当前权限数据
        $this_data = Permission::query()->where('id', $id)
            ->select('id', 'name', 'pid', 'cn_name')
            ->first();

        if (empty($this_data)) {
            return $this->response->errorBadRequest('错误，未查询到数据');
        }

        return $this->response->array(['data' => $this_data]);
    }

    /**
     * @param PermissionRequest $request
     * @param Permission $permission
     * @return Response
     */
    public function update(PermissionRequest $request, Permission $permission)
    {
        if ($request->hasAny('pid')) {
            $pid = Permission::query()
                ->select('pid')
                ->where('id', $request->input('pid'))
                ->first();
            if ($pid['pid'] != 0) {
                return $this->response->errorBadRequest('权限不能超过两级');
            }
        }
        // 更新权限数据
        $permission->update($request->all());

        return $this->response->noContent();
    }
}
